<?php
/**
count by where clause
<!--[count_from_db table="innoforum_topics" group_by="tpc_type_id" where="tpc_type_id = '3'"]-->
*/
function smarty_function_count_from_db ($params, &$smarty) 
{
    $table        = $params['table'];
    $where        = $params['where'];
    $label_count  = $params['label_count'];
    $extend_field = $params['extend_field'];
    $order_by     = $params['order_by'];
    $group_by     = $params['group_by'];
    $fixed        = $params['fixed'];
    $limit        = $params['limit'];
    $count_field  = (isset($params['count_field'])? $params['count_field']   : "*");

    $table = DBUtil::getLimitedTablename($table);

    if ($table&&$fixed){
      $where_fixed = "where ".$fixed." = ".$where;
      $sql = "SELECT COUNT($count_field) FROM $table $where_fixed $group_by $order_by";
      $column = array("count");
      $result = DBUtil::executeSQL($sql);
      $objectArray = DBUtil::marshallObjects ($result, $column);
      $value = $objectArray['0']['count'];
      if(!empty($value)){
        return $value;
      }
      return '0';

    }else if($table && $label_count){

      $where = DBUtil::_checkWhereClause($where);
      $order_by =DBUtil::_checkOrderByClause($order_by);
      $group_by =DBUtilEx::_checkGroupByClause($group_by);

      if($extend_field){
        $limit = "LIMIT 0,".$limit;
        $sql = "SELECT COUNT($count_field) $label_count ,$extend_field FROM $table $where $group_by $order_by $limit ";
      }else{
        $sql = "SELECT COUNT($count_field) $label_count FROM $table $where $group_by $order_by $limit";
      }

      $column = array("count","label");
      $result = DBUtil::executeSQL($sql);
      $objectArray = DBUtil::marshallObjects ($result, $column);

      if(!empty($objectArray)){
        $smarty->assign("user_reccommend", $objectArray);
        //$smarty->assign("user_reccommend", $value);
      }

    }else if ($table){
      $where = DBUtil::_checkWhereClause($where);
      $order_by =DBUtil::_checkOrderByClause($order_by);
      $group_by =DBUtilEx::_checkGroupByClause($group_by);

      $sql = "SELECT COUNT($count_field) FROM $table $where $group_by $order_by";
      $column = array("count");
      $result = DBUtil::executeSQL($sql);
      $objectArray = DBUtil::marshallObjects ($result, $column);
      $value = $objectArray['0']['count'];
      if(!empty($value)){
        return $value;
      }
      return '0';
    }

    //return true;
}
?>